//
//  HELSignInVC.m
//  HandheldELearn
//
//  Created by wsj2015 on 16/9/23.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "HELMySignInVC.h"

#import "HELSignInHeadView.h"
#import "HELMySignInCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "HELLocationHeader.h"
#import "UITableView+MTTHeaderFooterFittingHeight.h"
#import "UIView+RippleAnimation.h"
#import "HELSignResultVC.h"
#import "UINavigationController+WXSTransition.h"
#import "HELSignInInfor.h"
#import "JCAlertView.h"
@interface HELMySignInVC ()


@property (nonatomic, strong) HELSignInHeadView *unableHead;
@property (nonatomic, strong) HELLocationHeader *locationHead;

@property (nonatomic,  strong) NSArray *itemArr;

@property (nonatomic,  strong) UIButton *signBtn;

@property (nonatomic,  strong) HELSignInInfor *model;


@property (nonatomic,  strong) NSDictionary *address;


@end

@implementation HELMySignInVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    
    [self titleView:@"签到页面"];
    
    

    
    
}

- (NSArray *)itemArr{
    if (!_itemArr) {
//        课程名称 主办单位：联系人 开始时间 结束时间 课程描述
        _itemArr =@[@"课程名称",@"主办单位",@"联系人",@"联系方式",@"开始时间",@"结束时间",@"课程描述"];
    }
    return _itemArr;
}

#pragma mark ---请求后台是否可以签到的信息
//请求后台是否可以签到的信息     获取不到的信息返回首页
- (void)requestForSignInfor{
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//    dic[@"courseId"] = @11;
//    dic[@"signUser"] = @30;
//    dic[@"hospitalId"] = @500;
     dic[@"courseId"] = self.courseId;
    dic[@"hospitalId"] = [HELAppManager userInfo].hospitalId?[HELAppManager userInfo].hospitalId:@"";
    dic[@"signUser"] = HEL_USERID;
    weakSelf_define;
    [[HELNetworkManager sharedMg] POST:kQueryForSign parameters:dic success:^(NSDictionary * responseObject) {
        if (responseObject[@"exception"]) {
            [JCAlertView showOneButtonWithTitle:@"提示" Message:responseObject[@"exception"] ButtonType:JCAlertViewButtonTypeWarn ButtonTitle:@"返回" Click:^{
                [weakSelf.navigationController popToRootViewControllerAnimated:YES];
            }];
            return ;
        }
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
          HELSignInInfor *model = [HELSignInInfor mj_objectWithKeyValues:responseObject];
            weakSelf.model = model;
          
//           SURE_SIGN("可签到"),NOT_START("未到时间"),OVERDUE("已过期"),ALREADY_SIGN("已签到")
            if ([model.signType isEqualToString:@"SURE_SIGN"]) {
                
                //可以签到
                weakSelf_define;
                weakSelf.locationHead = [HELLocationHeader locationHeadView];
                weakSelf.locationHead.observeAddressBlock = ^(NSDictionary *address){
                    if (!address) {
                        weakSelf.signBtn.enabled = NO;
                    }else{
                        weakSelf.address = address;
                        weakSelf.signBtn.enabled = YES;
                    }
                    [weakSelf.tableView
                     mtt_updateTableHeaderViewHeightWithConfig:^(id view) {
                         
                     }
                     animated:YES];
                };
              
            
                weakSelf.tableView.tableHeaderView = self.locationHead;
                //        self.locationHead.frame = CGRectMake(0, 0, kScreenWidth, 160 * f);
                [weakSelf.tableView mtt_updateTableHeaderViewHeightWithAnimated:NO];
                [weakSelf.locationHead addObserver:self forKeyPath:@"statue" options:NSKeyValueObservingOptionNew context:nil];
                UIView *bgView = [UIView new];
                bgView.frame = CGRectMake(0, 0, kScreenWidth, 39);
                bgView.backgroundColor = [UIColor clearColor];
                [bgView addSubview:self.signBtn];
                weakSelf.tableView.tableFooterView = bgView;
                [weakSelf.tableView reloadData];
                [weakSelf.locationHead startLoaction];
                //不可以签到
            }else  {
                CGFloat f = kScreenFactor;
                weakSelf.unableHead = [HELSignInHeadView unableHeadView];
                NSString *titleStr ;
                NSString *resonStr ;
//                self.unableHead.sgin_icon.image = [UIImage imageNamed:@"sign_"];
                if ([model.signType isEqualToString:@"NOT_START"]) {
                    titleStr = @"很遗憾,签到失败!";
                    resonStr = @"课程还未开始";
                }
                if ([model.signType isEqualToString:@"OVERDUE"]) {
                    titleStr = @"很遗憾,签到失败!";
                    resonStr = @"课程已结束";
                }
                if ([model.signType isEqualToString:@"ALREADY_SIGN"]) {
                    titleStr = @"您已签到过了!";
                    resonStr = @"不能重复签到";
                }
                weakSelf.unableHead.titleL.text = titleStr;
                weakSelf.unableHead.reasonL.text = resonStr;
                weakSelf.unableHead.frame = CGRectMake(0, 0, kScreenWidth, 160 * f);
                weakSelf_define;
                weakSelf.unableHead.back = ^(){
                    [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                };
                weakSelf.tableView.tableHeaderView = weakSelf.unableHead;
                
                 [weakSelf.tableView reloadData];
            }

        }
        
    } failure:^(NSString *err) {
        weakSelf_define;
        [JCAlertView showOneButtonWithTitle:@"提示" Message:err ButtonType:JCAlertViewButtonTypeWarn ButtonTitle:@"返回" Click:^{
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
        }];
        
    }];
    
  

}

#pragma mark ---开始签到请求

- (void)requestToSign{
   
    if (!self.address) {
        return;
    }
    
   MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
  
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//    dict[@"courseId"] = @11;
//    dict[@"signUser"] = @30;
//   
//    dict[@"hospitalId"] = @500;
    
    dict[@"signAddress"] =self.address[@"address_address"];
    dict[@"signLat"] = self.address[@"address_lat"];
    dict[@"signLng"] = self.address[@"address_long"];
    dict[@"courseId"] = self.courseId;
    dict[@"hospitalId"] = [HELAppManager userInfo].hospitalId?[HELAppManager userInfo].hospitalId:@"";
    dict[@"signUser"] = HEL_USERID;
    weakSelf_define;
    [[HELNetworkManager sharedMg] POST:kSignInToServer parameters:dict success:^(id responseObject) {
       
        if (responseObject[@"exception"]) {
            cwqAlertMessage(responseObject[@"exception"]);
        }else{
             [hud hideAnimated:YES];
//            [self.navigationController wxs_pushViewController:[HELSignResultVC new] makeTransition:^(WXSTransitionProperty *transition) {
//                transition.backGestureEnable = NO;
//                transition.animationType = WXSTransitionAnimationTypeFragmentShowFromBottom;
//            }];
            [weakSelf.navigationController pushViewController:[HELSignResultVC new]  animated:YES];
           
        }
     
        
    } failure:^(NSString *err) {
       
        cwqAlertMessage(err);
        
    }];
   
 
    
    
}

- (void)configUI{
  
    [self.tableView registerNib:[UINib nibWithNibName:@"HELMySignInCell" bundle:nil] forCellReuseIdentifier:@"HELMySignInCell"];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64);
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self requestForSignInfor];
    

    
}
- (UIButton *)signBtn{
    if (!_signBtn) {
        _signBtn =[UIButton buttonWithType:UIButtonTypeSystem];
        _signBtn.rippleAnimationEnable = YES;
        [_signBtn setTitle:@"确认签到" forState:UIControlStateNormal];
        [_signBtn setBackgroundImage:[UIImage imageNamed:@"btn_bg_normal"] forState:UIControlStateNormal];
         [_signBtn setBackgroundImage:[UIImage imageNamed:@"btn_bg_disabled"] forState:UIControlStateDisabled];
        [_signBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_signBtn addTarget:self action:@selector(requestToSign) forControlEvents:UIControlEventTouchUpInside];
        _signBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        _signBtn.layer.masksToBounds = YES;
        _signBtn.layer.cornerRadius = 8;
        CGFloat f = kScreenFactor;
        CGFloat w = 140 *f;
        _signBtn.frame = CGRectMake(kScreenWidth/2 -w/2 , 0, w, 39);
        
        _signBtn.enabled = NO;
    }
    return _signBtn;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"statue"]) {
        NSNumber *value = change[@"new"];
        if (value.integerValue == 1) {
            self.signBtn.enabled = YES;
        }else{
         self.signBtn.enabled = NO;
        }
    }
}

- (void)dealloc{
    if (_locationHead) {
        [_locationHead removeObserver:self forKeyPath:@"statue"];
    }
   
}

- (void)viewWillDisappear:(BOOL)animated{
  
   
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (!self.model) {
        return  0;
    }
    return self.itemArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HELMySignInCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HELMySignInCell" forIndexPath:indexPath];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
  
    paragraphStyle.firstLineHeadIndent = 0.0f;
    paragraphStyle.lineSpacing = 8.0f;
   NSMutableAttributedString *mulStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@:   ",self.itemArr[indexPath.row]] attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:17],NSParagraphStyleAttributeName:paragraphStyle}];
 
    NSAttributedString *appendStr;
    switch (indexPath.row) {
        case 0:
          appendStr = [[NSAttributedString alloc] initWithString:self.model.courseName attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],NSParagraphStyleAttributeName:paragraphStyle}];
            break;
        case 1:
            appendStr = [[NSAttributedString alloc] initWithString:self.model.courseHospitalName attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
            break;
        case 2:
              appendStr = [[NSAttributedString alloc] initWithString:self.model.contacts attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
            break;
        case 3:
            appendStr = [[NSAttributedString alloc] initWithString:self.model.contactsPhone attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
            break;
        case 4:
             appendStr = [[NSAttributedString alloc] initWithString:self.model.courseStartShow attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
            break;
        case 5:
              appendStr = [[NSAttributedString alloc] initWithString:self.model.courseEndShow attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
            break;
        case 6:
            appendStr = [[NSAttributedString alloc] initWithString:self.model.courseDesc attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],NSParagraphStyleAttributeName:paragraphStyle}];
            
      
            break;
            
        default:
            break;
    }
    [mulStr appendAttributedString:appendStr];

    cell.contentL.attributedText = mulStr;
    return cell;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
  
     
        return  [tableView fd_heightForCellWithIdentifier:@"HELMySignInCell" configuration:^(HELMySignInCell * cell) {
            
            NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
            
            paragraphStyle.firstLineHeadIndent = 0.0f;
            paragraphStyle.lineSpacing = 8.0f;
            NSMutableAttributedString *mulStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@:   ",self.itemArr[indexPath.row]] attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:17],NSParagraphStyleAttributeName:paragraphStyle}];
            
            NSAttributedString *appendStr;
            switch (indexPath.row) {
                case 0:
                    appendStr = [[NSAttributedString alloc] initWithString:self.model.courseName attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],NSParagraphStyleAttributeName:paragraphStyle}];
                    break;
                case 1:
                    appendStr = [[NSAttributedString alloc] initWithString:self.model.courseHospitalName attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
                    break;
                case 2:
                    appendStr = [[NSAttributedString alloc] initWithString:self.model.contacts attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
                    break;
                case 3:
                    appendStr = [[NSAttributedString alloc] initWithString:self.model.contactsPhone attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
                    break;
                case 4:
                    appendStr = [[NSAttributedString alloc] initWithString:self.model.courseStartShow attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
                    break;
                case 5:
                    appendStr = [[NSAttributedString alloc] initWithString:self.model.courseEndShow attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
                    break;
                case 6:
                    appendStr = [[NSAttributedString alloc] initWithString:self.model.courseDesc attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],NSParagraphStyleAttributeName:paragraphStyle}];
                    
                    
                    break;
                    
                default:
                    break;
            }
            [mulStr appendAttributedString:appendStr];
            
            cell.contentL.attributedText = mulStr;

        }];

  
  
  }
@end
